package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.ManagerQuestion;
import com.ruoyi.system.service.IManagerQuestionService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 题库管理Controller
 *
 * @author ruoyi
 * @date 2025-06-13
 */
@RestController
@RequestMapping("/system/question")
public class ManagerQuestionController extends BaseController
{
    @Autowired
    private IManagerQuestionService managerQuestionService;
    @Value("${pdf.upload.adddrss}")
    private String UPLOAD_PDF;

    /**
     * 查询题库管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:question:list')")
    @GetMapping("/list")
    public TableDataInfo list(ManagerQuestion managerQuestion)
    {
        startPage();
        List<ManagerQuestion> list = managerQuestionService.selectManagerQuestionList(managerQuestion);
        return getDataTable(list);
    }

    /**
     * 导出题库管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:question:export')")
    @Log(title = "题库管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ManagerQuestion managerQuestion)
    {
        List<ManagerQuestion> list = managerQuestionService.selectManagerQuestionList(managerQuestion);
        ExcelUtil<ManagerQuestion> util = new ExcelUtil<ManagerQuestion>(ManagerQuestion.class);
        return util.exportExcel(list, "题库管理数据");
    }

    /**
     * 获取题库管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:question:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(managerQuestionService.selectManagerQuestionById(id));
    }

    /**
     * 新增题库管理
     */
    @PreAuthorize("@ss.hasPermi('system:question:add')")
    @Log(title = "题库管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ManagerQuestion managerQuestion)
    {
        return toAjax(managerQuestionService.insertManagerQuestion(managerQuestion));
    }

    /**
     * 修改题库管理
     */
    @PreAuthorize("@ss.hasPermi('system:question:edit')")
    @Log(title = "题库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ManagerQuestion managerQuestion)
    {
        return toAjax(managerQuestionService.updateManagerQuestion(managerQuestion));
    }

    /**
     * 删除题库管理
     */
    @PreAuthorize("@ss.hasPermi('system:question:remove')")
    @Log(title = "题库管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(managerQuestionService.deleteManagerQuestionByIds(ids));
    }

    @Log(title = "试题解析导入", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/examImport")
    public AjaxResult examImport(@RequestParam("file") MultipartFile[] multipartFiles) throws IOException {

        File fileDir = new File(UPLOAD_PDF);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        multipartFiles[0].transferTo(new File(fileDir, multipartFiles[0].getOriginalFilename()));

        //读取题组

        String title=multipartFiles[0].getOriginalFilename();
        title=title.substring(0,title.indexOf("."));
        Map map=managerQuestionService.selectManagerQuestionByGroup(title);
        String content= (String) map.get("content");
        String[] arry=content.split(",");
        map.put("array",arry);

        List<ManagerQuestion> list =managerQuestionService.selectManagerQuestion(map);


        String filePath = "F:\\pdf\\"+multipartFiles[0].getOriginalFilename();
        // 使用FileInputStream读取Excel文件
        try {

            FileInputStream fis = new FileInputStream(new File(filePath));
            // 创建XSSFWorkbook对象
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            // 获取第一个工作表（Sheet）
            Sheet sheet = workbook.getSheetAt(0);
            // 获取Sheet的第一个行号和最后一个行号hs.getLastRowNum();
            int last = sheet.getPhysicalNumberOfRows()-2;

            for (int j = 1; j <= last; j++) {
                // 从第二行开始读取数据
                Row row = sheet.getRow(j);
                ManagerQuestion f=new ManagerQuestion();
                for (int s = 0; s <= 1; s++){
                    try {
                        Cell cell=row.getCell(s);
                        if (cell.getCellType() != CellType.BLANK && (cell.getCellType() != CellType.STRING || cell.getStringCellValue().trim().length() > 0)) {
                             System.out.println(cell.getStringCellValue());
                            if (s==1){
                                String excela= filterChinese(cell.getStringCellValue());
                                 for (int m = 0; m <= list.size(); m++){
                                     f=list.get(m);
                                     String subject=filterChinese(f.getSubject());
                                     System.out.println(subject);
                                     if (excela.equals(subject)){
                                         f.setAnswerkeys(row.getCell(0).getStringCellValue());
                                         int n=managerQuestionService.updateManagerQuestion(f);
                                         System.out.println(subject);
                                         System.out.println(j+"行更新成功");
                                     }
                                }
                                System.out.println(excela);
                            }

                        }
                    }catch (Exception e){
                        System.out.println(j+"行读取错误");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return AjaxResult.success(1);
    }
    public static String filterChinese(String input) {
        if (input == null) return "";
        return input.replaceAll("[^\\u4E00-\\u9FFF]+", "");
    }
}
